package admin.shell.commands;

import game.MatchStatistics;
import game.Player;

import java.util.List;

import admin.exceptions.UnknownUserException;
import admin.ui.ProxyMediator;

public class UserDetailsCommand extends ShellCommand {

	@SuppressWarnings("unchecked")
	@Override
	public void execute(ProxyMediator proxy, String[] parameters) {
		if (parameters.length != 2) {
			System.out.println("Usage: user <username>");
			return;
		}
		
		String login = parameters[1];
			
		Object[] details;
		try {
			details = proxy.userDetails(login);
			Player player = (Player) details[0];
			List<MatchStatistics> oldMatchs = (List<MatchStatistics>) details[1];
			List<MatchStatistics> activeMatchs = (List<MatchStatistics>) details[2];
			
			System.out.print("Login   : " + player.getLogin() + "\n"
					       + "Ranking : " + player.getRanking() + "\n"
					       + "Status  : " + (player.isOnline() ? "online" : "offline") + "\n"
					       + "Role    : " + player.getRole() + "\n\n");
			
			if (oldMatchs.size() == 0) {
				System.out.println("No matchs in history");
			} else {
				System.out.println("Match history");
				printMatchList(oldMatchs);
			}
			
			if (activeMatchs.size() == 0) {
				System.out.println("\nNo active matchs");
			} else {
				System.out.println("\nActive matchs");
				printMatchList(activeMatchs);
			}
		} catch (UnknownUserException e) {
			System.out.println("Unknown user: " + e.getLogin());
		}
		
	}

	private void printMatchList(List<MatchStatistics> matchs) {
		
		System.out.printf("%10s  %-20s %-30s %s\n", "ID", "Game", "Date started", "Players");
		
		for (MatchStatistics match : matchs) {	
			String playersStr = "";
			for (String playerName : match.getPlayers()) {
				if (match.getWinner() != null && match.getWinner().equals(playerName)) {
					playersStr += "[" + playerName + "], ";
				} else {
					playersStr += playerName + ", ";
				}
			}
			playersStr = playersStr.substring(0, playersStr.length() - 2);
			System.out.printf("%10d  %-20s %-30s %s\n", match.getMatchId(), match.getGameName(), match.getDateStarted() != null ? match.getDateStarted() : "n/a", playersStr);
		}
		
		System.out.println("\nTotal: " + matchs.size());
	}

}
